
import { defineStore } from "pinia";
import { loginApi, getUserInfoApi, getUserMenusApi } from "@/api/auth";
import { buildRoutesFromMenus } from "@/utils/menu";
import router from "@/router/index";

export interface MenuItem {
    menuId: number;
    menuCode: string;
    menuName: string;
    menuType: string; // 'M'/'C'
    menuPreId?: number | null;
    menuUrl?: string | null;
    menuOrder?: number;
    child?: MenuItem[];
}

export const useUserStore = defineStore("user", {
    state: () => ({
        token: localStorage.getItem("TOKEN") || "",
        userName: "",
        nikeName: "",
        roleCode: "",
        orgCode: "",
        userId: null,
        powers: [] as String[],
        menus: [] as MenuItem[],
        dynamicAdded: false
    }),
    actions: {
        async login(username: string, password: string) {
            //@ts-ignore
            const { code, data } = await loginApi({ username, password });
            if (code === 200 && data) {
                this.token = data; // data 形如 "Bearer xxx"
                localStorage.setItem("TOKEN", this.token);
                await this.fetchProfileAndMenus();
                router.replace("/");
            } else {
                throw new Error("登录失败");
            }
        },
        async fetchProfileAndMenus() {
            const info = await getUserInfoApi();
            //@ts-ignore
            if (info?.code === 200) {
                this.userName = info.data?.userName || "";
                this.userId = info.data?.userId || null;
                this.orgCode = info.data?.orgCode || "";
                this.nikeName = info.data?.nikeName || "";
                this.roleCode = info.data?.roleCode || "";
                this.powers = info.data?.powers || [];
            }
            const menu = await getUserMenusApi();
            //@ts-ignore
            if (menu?.code === 200) {
                this.menus = menu.data || [];
                // 动态路由
                const dynamicRoutes = buildRoutesFromMenus(this.menus);
                dynamicRoutes.forEach(r => {
                    if (!router.hasRoute(r.name as string)) {
                        router.addRoute("Layout", r);
                    }
                });

                router.addRoute({
                    path: "/:pathMatch(.*)*",
                    name: "404",
                    component: () => import("@/views/NotFound.vue"),
                    meta: { title: "未找到" }
                });
                this.dynamicAdded = true;
            }
        },
        logout() {
            this.token = "";
            localStorage.removeItem("TOKEN");
            this.menus = [];
            this.dynamicAdded = false;
            router.replace("/login");
        }
    }
});